#include "unp.h"

int main() {
	int fd;
	struct sockaddr_in serv_addr, src_addr;
	socklen_t src_addr_len;
	char buf[MAXLINE], ip[16];
	int n;

	if((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		err_exit("socket() error.");
	}
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(9987);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(fd,(struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)
		err_exit("bind error");

	for(;;) {
		src_addr_len = sizeof(src_addr);
		if((n = recvfrom(fd, buf, MAXLINE, 0, (struct sockaddr*)&src_addr, &src_addr_len)) >= 0) {
			printf("recvfrom [%s:%u]\n", inet_ntop(AF_INET,&src_addr.sin_addr, ip, 16), ntohs(src_addr.sin_port));
			if(sendto(fd, buf, strlen(buf), 0, (struct sockaddr*)&src_addr, sizeof(src_addr)) == -1)
				err_sys("sendto error");
		}
		if(n == -1) {
			err_sys("recvfrom error.");
			break;
		}
	}
	return 0;
}
